<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* MODULE NAME   : event.php
*
* DESCRIPTION   : Event module controller
*
* MODIFICATION HISTORY
*   V1.0   2007-04-21 12:01 PM   - Dennis T. Kaplan     - Created
*
* @package             Calendar
* @subpackage          event component Class
* @author              Dennis T. Kaplan
* @copyright           Copyright (c) 2006-2007 PzzAzz
* @since               Version 1.0
* @filesource
*/


class Event extends Controller {
    
    
    function setVars()
    {
		$this->tpl['title'] = 'Events';
        $this->tpl['head'] = '';
        $this->tpl['body'] = '';
        $this->tpl['sidebar'] = 'Test';
		$this->uid = $this->session->userdata('uid');
        $this->dbtable = 'calendar';
        define('URI',$this->uri->segment(1).'/'.$this->uri->segment(2));
	}
    
    function __construct() 
    {
        parent::Controller();
        log_message('info', 'Event Controller initiated');
        //$this->load->library('profiler');
        $this->auth->CheckTaMeR(11,100);
        $this->setVars();
        $this->load->model('tamer_model', 'tm');
        //$this->load->model('calendar', 'bbm');
    }
    
    /**
    * @note	index
    * @info	Just forwarding
    * @author	Dennis T. Kaplan
    * @access	public
    * @param	 
    * @return	html page
    */	
    public function index()
    {
    	redirect('/calendar/event/browse', 'location');
    }
    
    public function browse() 
    {
        $rowcount = $this->db->count_all($this->dbtable);
        $this->db->select('Name, code AS Postcode, Starts, Ends, Active, '.$this->dbtable.'.id');
        $this->db->join('places_postcode', 'places_postcode.id = '.$this->dbtable.'.Postcode');
        $limit_to = 10;
        $this->db->limit($limit_to, $this->uri->segment(4,0));
        
        $query = $this->db->get($this->dbtable);
        
        $this->load->library('table');
        $this->load->helper('img');
        
        if ($query->num_rows() > 0) {
            foreach($query->result_array() as $row){
                if($this->auth->CheckTaMeR('1'))
                {
                    $row['Action'] = delete_icon(URI.'/delete/');
                }
                unset($row['id']);
                $this->table->add_row($row);
            }
            $this->table->set_heading(array_keys($row));
            
            $this->tpl['body'] .= $this->table->generate();
            $this->table->clear();      
            
            $this->load->library('pagination');
            $config['base_url']     = site_url($this->uri->segment(1).'/'.$this->uri->segment(2).'/'.$this->uri->segment(3).'/');
            $config['total_rows']   = $rowcount;
            $config['per_page']     = $limit_to;
            $this->pagination->initialize($config);
            $this->tpl['body'] .= $this->pagination->create_links();
        }else{
            $this->tpl['body'] .= 'No events to show';
        }
        $this->load->view('blank', $this->tpl);
    }
    
    
    public function addedit()
    {
        log_message('info', 'addedit initiated');
        if($this->input->post('save') !== FALSE)
        {
            $this->id = $this->input->post('id');
            if($this->id < 1) $this->id = FALSE;
            $this->dbdata = $this->tm->initdb($this->id);
            if ($this->validate() === TRUE){
                log_message('info', 'Validation OK');
            	$this->save(); //need to enter success message
                //redirect('/calendar/event/browse', 'location');
            }else{
                log_message('info', 'Validation error');
            }
        }
        $this->form();
    }
    
    /**
     * @note	display
     * @info	Display single event details
     * @author	Dennis T. Kaplan
     * @access	public
     * @param	 
     * @return	html
     */	
    public function display()
    {
    	$id = $this->uri->segment(4);
        $this->db->where('id', $id);
        $this->db->limit(1);
        $query = $this->db->get($this->dbtable);
        
        if($query->num_rows() > 0)
        {
            $row = $query->row();
            $this->db->select('code AS Postcode');
            $this->db->where('id', $row->Postcode);
            $this->db->limit(1);
            $query = $this->db->get('places_postcode');            
            $rowp = $query->row();
            
            $this->tpl['body'] .= "<dl>\n";            
            foreach($row as $k=>$v)
            {
                if($k != 'id' && $k != 'user_id'){
                    if($k == 'Postcode') $v = $rowp->Postcode;
                    if($k == 'Website') $v = auto_link($v, 'url', TRUE);
                    $this->tpl['body'] .= "\t<dt>$k</dt>\n";
                    $this->tpl['body'] .= "\t\t<dd>$v</dd>\n";
                }
            }
            $this->tpl['body'] .= "</dl>\n";
        }
        $this->load->view('blank', $this->tpl);
    }

    
    /**
    * @note	validate
    * @info	Validate submited form
    * @author	Dennis T. Kaplan
    * @access	private
    * @param	 
    * @return	TRUE || FALSE
    */	
    private function validate()
    {
        log_message('info', 'Validation initiated');
        $this->load->library('validation');
        $rules['Name']		= "trim|required|min_length[5]|max_length[30]|xss_clean";
        $rules['Address']   = "trim|required|min_length[5]|max_length[40]|xss_clean";
        $rules['Postcode']	= "trim|numeric|min_length[1]|max_length[11]";
        $rules['Starts']	= "trim|date_sql";
        $rules['Ends']		= "trim|date_sql";
        $rules['Website']	= "trim|required|min_length[5]|max_length[40]|xss_clean";
        $rules['Info']		= "trim|required|min_length[5]|max_length[2000]|xss_clean";
        
        $this->validation->set_rules($rules);
        $valResult = $this->validation->run();
        $this->post = array();;
        foreach($this->dbdata as $k=>$v)
        {
            if(isset($this->validation->$k)){
                $p = $this->validation->$k;
                if($p != $v){
                    $this->post[$k] = $p;
                }
            }
        }
        
        if($valResult === FALSE)
        {
            $this->tpl = array_merge($this->tpl, $this->dbdata, $this->post);
            unset($this->post);
            return FALSE;
        }else{
            return TRUE;
        }
    }
    
    
    private function form()
    {
        $this->tpl['tpljs'][]  = 'jquery';
        $this->tpl['tplcss'][]  = 'calendar';
        $this->tpl['tpljs'][]  = 'calendar';
        $this->tpl['tpljs'][]  = 'jquery.bgiframe.min';
        $this->tpl['tpljs'][]  = 'jquery.dimensions';
        $this->tpl['tplcss'][]  = 'jquery.autocomplete';
        $this->tpl['tpljs'][]  = 'jquery.autocomplete';
        $this->tpl['tpljs'][]  = 'postcode';
        
        $action = $this->uri->segment(4);
        $id = $this->uri->segment(5);
        
        if( ! isset($this->dbdata)) {
            if($id < 1) $id = FALSE;
            $this->dbdata = $this->tm->initdb($id);
        }
        extract($this->dbdata);
        
        $attributes = array('name' => 'event');
        $this->load->helper('form');
        $form['Name'] = form_input(array(
        'name'        => 'Name',
        'id'          => 'Name',
        'value'       => $Name,
        'maxlength'   => '30',
        'size'        => '30',
        'style'       => ''
        )
        );
        
        $form['Address'] = form_input(array(
        'name'        => 'Address',
        'id'          => 'Address',
        'value'       => $Address,
        'maxlength'   => '200',
        'size'        => '40',
        'style'       => ''
        )
        );
        
        $form['Postcode or City'] =  form_input(array(
        'name'        => 'Postcode',
        'id'          => 'Postcode',
        'value'       => $Postcode,
        'size'        => '10',
        'onclick'     => 'clearValue(this)'
        )
        ).'<span id="postresult"></span>';
        
        $form[2]['Start Date'] = form_input(array(
        'name'        => 'Starts',
        'id'          => 'Starts',
        'value'       => $Starts,
        'maxlength'   => '10',
        'size'        => '10',
        'style'       => 'width: 100px',
        'class'       => 'calendarSelectDate'
        )
        );
        
        $form[2]['End Date'] = form_input(array(
        'name'        => 'Ends',
        'id'          => 'Ends',
        'value'       => $Ends,
        'maxlength'   => '10',
        'size'        => '10',
        'style'       => 'width: 100px',
        'class'       => 'calendarSelectDate'
        
        )
        );
        $form['Website'] = form_input(array(
        'name'        => 'Website',
        'id'          => 'Website',
        'value'       => $Website,
        'maxlength'   => '200',
        'size'        => '40',
        'style'       => ''
        )
        );
        
        $form['Info'] = form_textarea(array(
        'name'        => 'Info',
        'id'          => 'Info',
        'value'       => $Info,
        'rows'        => '15',
        'cols'        => '60',
        'style'       => ''
        )
        );
        $form[''] =          form_submit(array('class' => 'submit', 
        'name'        => 'save',
        'value'       => 'Save',
        'style'       => 'margin:10px'
        )
        );
        
        $this->load->library('table');
        $this->tpl['body'] .=  form_open(URI.'/addedit', $attributes);
        $this->tpl['body'] .= $this->table->form_table($form);
        $this->tpl['body'] .= form_hidden('id', $id);
        $this->tpl['body'] .= '</form>';
        $this->tpl['body'] .= '<p><span id="resulttag"></span></p>';
        $this->load->view('blank', $this->tpl);
    } 
    
    
    
    private function save()
    {
        log_message('info', 'Save initiated');
        $this->post['user_id'] = $this->uid;
        if(isset($this->id) && $this->id > 0)
        {
            $this->db->where('id', $this->id);
            $this->db->update($this->dbtable, $this->post); 
        }else{
            $this->db->insert($this->dbtable, $this->post);
        }
    }
    
    public function delete()
    {
        $id = $this->uri->segment(4);
        if($id !== FALSE && ctype_digit($id))
        {
            $this->db->delete($this->dbtable, array('id'=>$id)); 
        }else{
        	$this->msg->setError('Could not delete: Object not found');
        }
        
        redirect('calendar/event', 'location');
    }
    
    private function _clear_form() {
        
        // ///////////////////////////////////////////////////////////////////////
        // NOTE: Set default values for the form here if you wish.
        // ///////////////////////////////////////////////////////////////////////
        $data['id']		= '';
        $data['Name']		= '';
        $data['postcode_id']		= '';
        $data['Starts']		= '';
        $data['Ends']		= '';
        $data['Map']		= '';
        $data['Website']		= '';
        $data['Info']		= '';
        $data['Active']		= '';
        $data['user_id']		= '';
        $data['updated']		= '';
        $data['added']		= '';
        
        return $data;
        
    }
    
    private function _get_form_values() {
        // ///////////////////////////////////////////////////////////////////////
        // NOTE: Perform customisation on the retrieved form values here if you wish.
        // ///////////////////////////////////////////////////////////////////////
        // XXS Filtering enforced for user input
        $data['id']		= $this->input->post('id', TRUE);
        $data['Name']		= $this->input->post('Name', TRUE);
        $data['postcode_id']		= $this->input->post('postcode_id', TRUE);
        $data['Starts']		= $this->input->post('Starts', TRUE);
        $data['Ends']		= $this->input->post('Ends', TRUE);
        $data['Map']		= $this->input->post('Map', TRUE);
        $data['Website']		= $this->input->post('Website', TRUE);
        $data['Info']		= $this->input->post('Info', TRUE);
        $data['Active']		= $this->input->post('Active', TRUE);
        $data['user_id']		= $this->input->post('user_id', TRUE);
        $data['updated']		= $this->input->post('updated', TRUE);
        $data['added']		= $this->input->post('added', TRUE);
        
        return $data;
        
    }
    
}
?>
